<template>
    <div id='blogs'>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>博客管理</el-breadcrumb-item>
            <el-breadcrumb-item>博客列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-tabs v-model="activeIndex" @tab-click="tabClick">
                <el-tab-pane :label="`全部(${typeof (this.all_total[0]) !== 'undefined' ? this.all_total[0] : 0})`"
                             name="0">
                    <!-- 搜索与添加区域 -->
                    <el-row>
                        <el-col :span="8">
                            <el-input class="input-select" placeholder="请输入关键词"
                                      v-model="queryInfo[activeIndex - '0'].title"
                                      @clear="getBlogList(0)"
                                      @keyup.enter.native="getBlogList(0)" clearable>
                                <el-select clearable @change="getBlogList(0)"
                                           v-model="queryInfo[activeIndex - '0'].typeIds" slot="prepend"
                                           placeholder="请选择分类">
                                    <el-option v-for="(item, index) in typeList" :key="index" :label="item.name"
                                               :value="item.id"></el-option>
                                </el-select>
                                <el-button slot="append" icon="el-icon-search" @click="getBlogList(0)"></el-button>
                            </el-input>
                        </el-col>
                        <el-col :offset="1" :span="4">
                            <el-button size="small" type="primary" @click="addBlog" icon="iconfont icon-writing-blogs">
                                新增博客
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-divider class="tl-margin-15-0"></el-divider>
                </el-tab-pane>
                <el-tab-pane :label="`公开(${typeof (this.all_total[1]) !== 'undefined' ? this.all_total[1] : 0})`"
                             name="1">
                </el-tab-pane>
                <el-tab-pane :label="`私密(${typeof (this.all_total[2]) !== 'undefined' ? this.all_total[2] : 0})`"
                             name="2">
                </el-tab-pane>
                <el-tab-pane :label="`草稿箱(${typeof (this.all_total[3]) !== 'undefined' ? this.all_total[3] : 0})`"
                             name="3">
                </el-tab-pane>
            </el-tabs>
            <!-- 博客列表区域 -->
            <el-table :data="blogList" border stripe> <!--max-height="360"-->
                <el-table-column align="center" type="index" label="#"></el-table-column>
                <el-table-column align="center" label="首图" width="100px">
                    <template slot-scope="scope">
                        <img class="tl-height-50 tl-border-radius-small" :src="scope.row.firstPicture" alt="">
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip align="center" prop="title" label="标题"></el-table-column>
                <el-table-column align="center" label="发布类型" width="80px">
                    <template slot-scope="scope" v-if="scope.row.flag !== ''">
                        <el-tag v-if="scope.row.flag === 'original'" type="danger">原创</el-tag>
                        <el-tag v-else-if="scope.row.flag === 'repost'" type="success">转载</el-tag>
                        <el-tag v-else>翻译</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="类型" width="300px">
                    <template slot-scope="scope">
                        <el-tag class="tl-margin-5" v-for="type in scope.row.types" :key="type.id" type="warning">
                            {{ type.name }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="推荐" width="70%">
                    <template slot-scope="scope">
                        <el-switch @change="recComChange(scope.row, 1)" v-model="scope.row.recommend"
                                   active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="评论" width="70%">
                    <template slot-scope="scope">
                        <el-tooltip :content="scope.row.commentable ? '允许评论': '禁止评论'" placement="top"
                                    :enterable="false">
                            <el-switch @change="recComChange(scope.row, 2)" v-model="scope.row.commentable"
                                       active-color="#409EFF" inactive-color="#ff4949"></el-switch>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="更新时间" width="185px">
                    <template slot-scope="scope">
                        {{ scope.row.updateTime | dateFormat('yyyy-MM-dd hh:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-row type="flex" justify="space-around">
                            <el-col :span="6">
                                <el-tooltip :enterable="false" :hide-after="500" content="查看" placement="top">
                                    <el-button type="success" icon="el-icon-view" size="mini"
                                               @click="viewBlog(scope.row.id)">
                                    </el-button>
                                </el-tooltip>
                            </el-col>
                            <el-col :span="6">
                                <el-tooltip :enterable="false" :hide-after="500" content="编辑" placement="top">
                                    <el-button type="primary" icon="el-icon-edit" size="mini"
                                               @click="editBlog(scope.row.id)">
                                    </el-button>
                                </el-tooltip>
                            </el-col>
                            <el-col :span="6">
                                <el-tooltip :enterable="false" :hide-after="500" content="删除" placement="top">
                                    <el-button type="danger" icon="el-icon-delete" size="mini"
                                               @click="removeBlog(scope.row.id)">
                                    </el-button>
                                </el-tooltip>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination background class="tl-margin-top-20 tl-text-center"
                           :current-page.sync="queryInfo[activeIndex - '0'].pageNum"
                           @current-change="handleCurrentChange"
                           layout="total, prev, pager, next, jumper"
                           :page-size="10"
                           :total="total">
            </el-pagination>
        </el-card>
    </div>
</template>

<script>
import { blogDelete, getBlogList, recom, total } from '@/api/blog/blog';
import { typesList } from '@/api/category/category';

export default {
    name: 'Blogs',
    components: {},
    data: function () {
        return {
            activeIndex: '0',
            queryInfo: [{
                status: null,
                typeIds: null,
                published: null,
                title: '',
                pageNum: 1
            }, {
                status: true,
                published: 'public',
                pageNum: 1
            }, {
                status: true,
                published: 'private',
                pageNum: 1
            }, {
                status: false,
                published: null,
                pageNum: 1
            }],
            total: 0,
            all_total: [],
            select: '',
            blogList: [],
            typeList: []
        }
    },
    methods: {
        tabClick: function () {
            this.getBlogList(this.activeIndex - '0')
        },
        viewBlog: function (id) {
            window.open(`/web/blog/${id}`, '_blank')
        },
        removeBlog: async function (id) {
            await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await blogDelete(id);
                if (res.code ^ 200) {
                    return this.$message({ showClose: true, message: res.msg, type: 'error' });
                }
                this.$message({ showClose: true, message: res.msg, type: 'success' });
                for (let i = 0; i < 4; i++) {
                    await this.getTotal(i)
                }
                await this.getBlogList(this.activeIndex - '0');
            }).catch(() => {
                this.$message({ showClose: true, type: 'info', message: '已取消删除' });
            });
        },
        editBlog: function (id) {
            this.$router.push({ path: '/admin/blog/add', query: { id: id } })
        },
        addBlog: function () {
            this.$router.push('/admin/blog/add')
        },
        getBlogList: async function (index) {
            const res = await getBlogList(this.queryInfo[index]);
            console.log(res)
            if (res.code ^ 200) {
                return this.$message({ showClose: true, message: res.msg, type: 'error' });
            }
            if (!res.data.rows.length && (this.queryInfo[index].pageNum ^ 1)) {
                this.queryInfo[index].pageNum--;
                return await this.getBlogList(index);
            }
            this.blogList = res.data.rows;
            if (index === 0) {
                await this.getTotal(0)
            } else if (index !== 0) {
                this.all_total[index] = res.data.total
            }
            this.total = res.data.total;
        },
        getTotal: async function (index) {
            const info = JSON.parse(JSON.stringify(this.queryInfo[index]))
            if (index === 0) {
                info.typeIds = null
                info.title = ''
            }
            const res = await total(info);
            console.log(res)
            if (res.code ^ 200) {
                return this.$message({ showClose: true, message: res.msg, type: 'error' });
            }
            this.all_total[index] = res.data
        },
        getTypeList: async function () {
            const res = await typesList();
            if (res.code ^ 200) {
                return this.$message({ showClose: true, message: res.msg, type: 'error' });
            }
            console.log(res)
            this.typeList = res.data;
        },
        handleCurrentChange: function (val) {
            this.queryInfo[this.activeIndex - '0'].pageNum = val;
            this.getBlogList(this.activeIndex - '0');
            console.log(`当前页: ${val}`);
        },
        recComChange: async function (val, index) {
            const res = await recom({
                id: val.id,
                commentable: val.commentable,
                recommend: val.recommend
            });
            if (res.code ^ 200) {
                this.$message({ showClose: true, message: res.msg, type: 'error' });
                if (index === 1) {
                    val.recommend = !val.recommend
                } else {
                    val.commentable = !val.commentable
                }
            } else {
                this.$message({ showClose: true, message: res.msg, type: 'success' });
            }
        }
    },
    created: function () {
        for (let i = 0; i < 4; i++) {
            this.getTotal(i)
        }
        this.getBlogList(0)
        this.getTypeList()
    }
}
</script>

<style lang='less' scoped>
#blogs ::v-deep .el-table td, ::v-deep .el-table th {
    padding: 10px 0;
}

.el-tabs {
    ::v-deep .el-tabs__item {
        font-weight: bold;
        font-size: 16px !important;
        padding: 0 30px;
    }
}

.el-input .el-select {
    width: 130px;
}

.input-select ::v-deep .el-input-group__prepend {
    background-color: #fff;
}
</style>
